package xyz.lisys.advice.web;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdviceAdapter;

import java.io.IOException;
import java.lang.reflect.Type;

@Slf4j
@RestControllerAdvice
public class CustomRequestBodyAdviceAdapter extends RequestBodyAdviceAdapter {
    // 通过注解 @RestControllerAdvice 注册到 RequestMappingHandlerAdapter 中
    // 自定义请求体的处理逻辑

    @Override
    public boolean supports(MethodParameter methodParameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        // 判断是否需要处理当前请求

        // 判断 Controller 的注解是否有 @DecodeBody 注解，如果没有的话，表示不需要进行解码，返回 false
        // return methodParameter.hasParameterAnnotation(DecodeBody.class);
        return true;
    }

    @Override
    public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) throws IOException {
        // 在请求体被反序列化为目标对象前执行

        log.info("CustomRequestBodyAdviceAdapter before body read");
        return super.beforeBodyRead(inputMessage, parameter, targetType, converterType);
    }
}
